import {
	ref,
	onMounted
} from 'vue';
import {
	onLoad,
	onShareAppMessage,
	// onShareTimeline
} from '@dcloudio/uni-app';


export function useWxShare(options = {}) {
	// 分享配置
	const shareConfig = ref({
		title: options.title || '考试',
		imageUrl: options.defaultImage || '',
		path: options.path || '',
	});

	// 设置分享内容
	const setShareContent = (content) => {
		shareConfig.value = {
			...shareConfig.value,
			...content
		};
	};

	// 处理分享事件
	onShareAppMessage((res) => {
		if (res.from === 'button') {
			console.log("button");
			// 来自页面内分享按钮
			setShareContent({
				title: res.target.dataset.title || shareConfig.value.title,
				imageUrl: res.target.dataset.image || shareConfig.value.imageUrl
			})
		} else {
			console.log(options);
			// 来自系统分享，从自定义函数获取信息
			const info = options?.getShareInfo ? options?.getShareInfo() : options;
			if (info) {
				setShareContent({
					title: info.title || shareConfig.value.title,
					imageUrl: info.imageUrl || shareConfig.value.imageUrl
				});
			}
		}

		// 触发分享回调（如埋点）
		if (options.onShare) {
			console.log('用户触发了分享');
			options.onShare();
		}

		return {
			...shareConfig.value
		};
	});

	/**
	 * @name 判断是否强制登录
	 * @param {String} mode  区分不同模块下的分享是否需要先登录
	 * @return {Boolean} 返回 ture / false
	 */
	const isForceLogin = (mode) => {
		// 判断是否强制登录
		// return true
	}

	/**
	 * @name 解析小程序码\二维码携带的参数
	 */
	const getShareInfo = async (scene) => {
		if (scene && scene !== 'undefined') {
			console.log('111scene', scene);
			// 处理scene逻辑...
			let obj = {
				scene: scene
			}
			// let res = await this.$http.getShareInfo(obj)

			return {
				id: 1111,
				type: 1
			}
			// 判断是否强制登录
			// isForceLogin()
		}

	};

	// 初始化
	onMounted(() => {
		// 获取当前页面参数
		const currentPage = getCurrentPages().pop();
		if (currentPage) {
			const {
				scene
			} = currentPage.options;
			if (scene) {
				console.log("scene", decodeURIComponent(scene || ''));

				getShareInfo(decodeURIComponent(scene || ''))
			} else {
				console.log("其他参数，", currentPage.options);
				// 处理其他分享参数
				if (currentPage.options.fromShareUserId) {
					console.log("处理其他分享参数", currentPage.options.fromShareUserId);
					uni.setStorageSync('inviteCode', currentPage.options.fromShareUserId);
				}
			}
		}
	});

	return {
		shareConfig,
		setShareContent,
		getShareInfo,
		onShareAppMessage
	};
}